package com.xr.maintain.service.impl;

import com.xr.maintain.entity.ResponseBo;
import com.xr.maintain.service.MaintainService;
import com.xr.maintain.service.TargetFoodService;
import com.xr.maintain.util.TypeClassEnum;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created on 2021/6/4
 * @author qiao
 * @Desc:
 */
@Service
@RequiredArgsConstructor
public class MaintainServiceImpl implements MaintainService {

    @Autowired
    private TargetFoodService targetFoodService;


    @Override
    public ResponseBo maintainByType(String type) {
        String s = TypeClassEnum.valueOf(type).get(targetFoodService);
        if (!StringUtils.isEmpty(s)) {
            return ResponseBo.fail(s);
        }
        return ResponseBo.ok();
    }

    @Override
    public ResponseBo maintainAll() {
        TypeClassEnum[] values = TypeClassEnum.values();
        List<String> errorList = new ArrayList<>();
        for (TypeClassEnum value : values) {
            String s = value.get(targetFoodService);
            if (!StringUtils.isEmpty(s)) {
                errorList.add(s);
            }
        }
        if (errorList.size() > 0) {
            return ResponseBo.fail(errorList.toString());
        }
        return ResponseBo.ok();
    }

    @Override
    public ResponseBo maintainAllThread() {
        TypeClassEnum[] values = TypeClassEnum.values();
        BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(30);
        List<String> failList = Collections.synchronizedList(new ArrayList<>());
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(4,6,60, TimeUnit.SECONDS,queue);
        for (TypeClassEnum value : values) {
            threadPoolExecutor.execute(new DoWork(value,failList));
        }
        threadPoolExecutor.shutdown();
        while(!threadPoolExecutor.isTerminated()) {}
        if (failList.size()>0){
            return ResponseBo.fail(failList.toString());
        }
        return ResponseBo.ok();
    }


    class DoWork implements Runnable{

        private TypeClassEnum value;

        private List<String> list;

        public DoWork(TypeClassEnum value, List<String> list) {
            this.value = value;
            this.list = list;
        }
        @Override
        public void run() {
            String s = value.get(targetFoodService);
            if (!StringUtils.isEmpty(s)){
                list.add(s);
            }
        }
    }


}
